class TreeNode(object):
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class CBTInserter(object):

    def __init__(self, root):
        """
        :type root: TreeNode
        """
        self.tree = root
        self.now_set = {}
        self.index = 0
        self.now_set[self.index] = root
        while True:
            node = self.now_set[self.index]
            if node.left:
                self.now_set[2 * self.index + 1] = node.left
                if node.right:
                    self.now_set[2 * self.index + 2] = node.right
                    self.index += 1
                else:
                    break
            else:
                break

    def insert(self, val):
        """
        :type val: int
        :rtype: int
        """
        new_node = TreeNode(val)
        r_val = self.now_set[self.index].val
        if 2 * self.index + 1 not in self.now_set:
            self.now_set[self.index].left = new_node
            self.now_set[2 * self.index + 1] = new_node
        else:
            self.now_set[self.index].right = new_node
            self.now_set[2 * self.index + 2] = new_node
            self.index += 1
        return r_val



    def get_root(self):
        """
        :rtype: TreeNode
        """
        return self.tree